import SwiftUI

// 检测对象数据模型
struct DetectedObjectItem: Identifiable {
    let id = UUID()
    let type: ObjectType
    let confidence: Double
    let location: String
    
    enum ObjectType: String {
        case person = "行人"
        case vehicle = "车辆"
        case obstacle = "障碍物"
        case animal = "动物"
        case face = "人脸"
    }
}

// 目标识别视图
struct ObjectDetectionView: View {
    @EnvironmentObject var tcpCarService: TCPCarService
    
    @State private var isDetecting = false
    @State private var selectedObjectType: DetectedObjectItem.ObjectType = .person
    @State private var confidenceThreshold = 0.7
    @State private var detectedObjects: [DetectedObjectItem] = []
    @State private var isTracking = false
    @State private var trackingObjectId: UUID?
    
    // 模拟检测结果
    let sampleObjects = [
        DetectedObjectItem(type: .person, confidence: 0.92, location: "左前方 3米"),
        DetectedObjectItem(type: .vehicle, confidence: 0.85, location: "右侧 5米"),
        DetectedObjectItem(type: .obstacle, confidence: 0.78, location: "前方 2米")
    ]
    
    var body: some View {
        ScrollView {
            VStack(spacing: 20) {
                // 标题
                Text("目标识别")
                    .font(.title)
                    .fontWeight(.bold)
                    .padding(.top)
                
                // 视频预览区域（模拟）
                ZStack {
                    Rectangle()
                        .fill(Color.black.opacity(0.8))
                        .cornerRadius(15)
                        .overlay(
                            Image(systemName: "camera.viewfinder")
                                .font(.system(size: 60))
                                .foregroundColor(.white.opacity(0.5))
                        )
                    
                    // 检测框（模拟）
                    if isDetecting {
                        ForEach(0..<3) { index in
                            Rectangle()
                                .strokeBorder(getColor(for: index), lineWidth: 2)
                                .frame(width: 80 + CGFloat(index * 30), height: 120 + CGFloat(index * 20))
                                .position(
                                    x: 100 + CGFloat(index * 80),
                                    y: 120 + CGFloat(index * 50)
                                )
                        }
                    }
                    
                    // 正在识别指示器
                    if isDetecting {
                        VStack {
                            Spacer()
                            HStack {
                                Circle()
                                    .fill(Color.red)
                                    .frame(width: 10, height: 10)
                                Text("正在识别")
                                    .foregroundColor(.white)
                            }
                            .padding(8)
                            .background(Color.black.opacity(0.5))
                            .cornerRadius(10)
                            .padding(.bottom, 10)
                        }
                    }
                }
                .frame(height: 250)
                .padding(.horizontal)
                
                // 控制面板
                VStack(spacing: 15) {
                    // 识别控制
                    HStack(spacing: 20) {
                        Button(action: {
                            isDetecting.toggle()
                            
                            if isDetecting {
                                // 开始识别，发送TCP命令
                                startDetection()
                                
                                // 模拟识别结果
                                DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
                                    detectedObjects = sampleObjects
                                }
                            } else {
                                // 停止识别，发送TCP命令
                                stopDetection()
                                detectedObjects = []
                            }
                        }) {
                            HStack {
                                Image(systemName: isDetecting ? "stop.fill" : "play.fill")
                                Text(isDetecting ? "停止识别" : "开始识别")
                            }
                            .padding()
                            .frame(maxWidth: .infinity)
                            .background(isDetecting ? Color.red : Color.green)
                            .foregroundColor(.white)
                            .cornerRadius(10)
                        }
                        
                        Button(action: {
                            isTracking.toggle()
                            
                            if isTracking && !detectedObjects.isEmpty {
                                // 选择第一个对象进行跟踪
                                trackingObjectId = detectedObjects.first?.id
                                // 发送跟踪命令
                                startTracking(objectType: detectedObjects.first?.type ?? .person)
                            } else {
                                // 停止跟踪
                                trackingObjectId = nil
                                stopTracking()
                            }
                        }) {
                            HStack {
                                Image(systemName: isTracking ? "location.slash.fill" : "location.fill")
                                Text(isTracking ? "停止跟踪" : "目标跟踪")
                            }
                            .padding()
                            .frame(maxWidth: .infinity)
                            .background(isTracking ? Color.orange : Color.blue)
                            .foregroundColor(.white)
                            .cornerRadius(10)
                        }
                        .disabled(detectedObjects.isEmpty)
                    }
                    
                    // 目标类型选择
                    VStack(alignment: .leading) {
                        Text("选择目标类型")
                            .font(.headline)
                        
                        Picker("目标类型", selection: $selectedObjectType) {
                            Text("行人").tag(DetectedObjectItem.ObjectType.person)
                            Text("车辆").tag(DetectedObjectItem.ObjectType.vehicle)
                            Text("障碍物").tag(DetectedObjectItem.ObjectType.obstacle)
                            Text("动物").tag(DetectedObjectItem.ObjectType.animal)
                            Text("人脸").tag(DetectedObjectItem.ObjectType.face)
                        }
                        .pickerStyle(SegmentedPickerStyle())
                    }
                    
                    // 置信度阈值调整
                    VStack(alignment: .leading) {
                        HStack {
                            Text("置信度阈值")
                                .font(.headline)
                            Spacer()
                            Text("\(Int(confidenceThreshold * 100))%")
                        }
                        
                        Slider(value: $confidenceThreshold, in: 0.5...0.95, step: 0.05)
                    }
                }
                .padding(.horizontal)
                
                // 检测结果列表
                if !detectedObjects.isEmpty {
                    VStack(alignment: .leading, spacing: 10) {
                        Text("检测结果")
                            .font(.headline)
                            .padding(.horizontal)
                        
                        VStack(spacing: 8) {
                            ForEach(detectedObjects) { object in
                                ObjectRow(
                                    object: object, 
                                    isTracking: isTracking && trackingObjectId == object.id,
                                    onTrack: {
                                        isTracking = true
                                        trackingObjectId = object.id
                                        startTracking(objectType: object.type)
                                    }
                                )
                                .padding(.horizontal)
                            }
                        }
                    }
                    .padding(.vertical)
                }
                
                // 底部间距，避免被标签栏遮挡
                Color.clear.frame(height: 20)
            }
            .padding(.bottom, 30)
        }
    }
    
    // 开始目标检测
    private func startDetection() {
        // 构建命令，根据选择的对象类型和阈值
        let typeCode: String
        switch selectedObjectType {
        case .person: typeCode = "P"
        case .vehicle: typeCode = "V"
        case .obstacle: typeCode = "O"
        case .animal: typeCode = "A"
        case .face: typeCode = "F"
        }
        
        let threshold = Int(confidenceThreshold * 100)
        let command = "DETECT:\(typeCode):\(threshold)"
        
        // 发送TCP命令
        if let data = command.data(using: .utf8) {
            tcpCarService.sendData(data) { success in
                print("检测命令发送\(success ? "成功" : "失败"): \(command)")
            }
        }
    }
    
    // 停止目标检测
    private func stopDetection() {
        let command = "DETECT:STOP"
        
        // 发送TCP命令
        if let data = command.data(using: .utf8) {
            tcpCarService.sendData(data) { success in
                print("停止检测命令发送\(success ? "成功" : "失败"): \(command)")
            }
        }
    }
    
    // 开始目标跟踪
    private func startTracking(objectType: DetectedObjectItem.ObjectType) {
        let typeCode: String
        switch objectType {
        case .person: typeCode = "P"
        case .vehicle: typeCode = "V"
        case .obstacle: typeCode = "O"
        case .animal: typeCode = "A"
        case .face: typeCode = "F"
        }
        
        let command = "TRACK:\(typeCode)"
        
        // 发送TCP命令
        if let data = command.data(using: .utf8) {
            tcpCarService.sendData(data) { success in
                print("跟踪命令发送\(success ? "成功" : "失败"): \(command)")
            }
        }
    }
    
    // 停止目标跟踪
    private func stopTracking() {
        let command = "TRACK:STOP"
        
        // 发送TCP命令
        if let data = command.data(using: .utf8) {
            tcpCarService.sendData(data) { success in
                print("停止跟踪命令发送\(success ? "成功" : "失败"): \(command)")
            }
        }
    }
    
    // 获取检测框颜色
    private func getColor(for index: Int) -> Color {
        switch index {
        case 0: return .red
        case 1: return .blue
        case 2: return .green
        default: return .yellow
        }
    }
}

// 检测对象行
struct ObjectRow: View {
    let object: DetectedObjectItem
    let isTracking: Bool
    let onTrack: () -> Void
    
    var body: some View {
        HStack {
            // 对象类型图标
            Image(systemName: getIcon(for: object.type))
                .font(.title2)
                .foregroundColor(getColor(for: object.type))
                .frame(width: 40)
            
            // 对象信息
            VStack(alignment: .leading) {
                Text(object.type.rawValue)
                    .font(.headline)
                
                HStack {
                    Text("置信度: \(Int(object.confidence * 100))%")
                        .font(.caption)
                    Text("•")
                    Text(object.location)
                        .font(.caption)
                }
                .foregroundColor(.secondary)
            }
            
            Spacer()
            
            // 跟踪按钮
            Button(action: onTrack) {
                Image(systemName: isTracking ? "location.fill" : "location")
                    .foregroundColor(isTracking ? .blue : .gray)
                    .padding(8)
                    .background(
                        Circle()
                            .fill(Color(.systemGray6))
                    )
            }
        }
        .padding(.vertical, 5)
    }
    
    // 获取对象类型图标
    private func getIcon(for type: DetectedObjectItem.ObjectType) -> String {
        switch type {
        case .person: return "person.fill"
        case .vehicle: return "car.fill"
        case .obstacle: return "exclamationmark.triangle.fill"
        case .animal: return "hare.fill"
        case .face: return "person.crop.square.fill"
        }
    }
    
    // 获取对象类型颜色
    private func getColor(for type: DetectedObjectItem.ObjectType) -> Color {
        switch type {
        case .person: return .blue
        case .vehicle: return .green
        case .obstacle: return .red
        case .animal: return .orange
        case .face: return .purple
        }
    }
}

// 预览
struct ObjectDetectionView_Previews: PreviewProvider {
    static var previews: some View {
        ObjectDetectionView()
            .environmentObject(TCPCarService())
    }
} 